"""

"""

import os
import sys
import logging
from pathlib import Path
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager
from kivy.logger import Logger
from kivy.core.text import LabelBase
from kivy.config import Config

from ..core import setup_logging
from .windows.main_window import MainWindow
from .windows.upload_window import UploadWindow
from .windows.processing_window import ProcessingWindow
from .windows.result_window import ResultWindow
from .windows.settings_window import SettingsWindow

class DesktopApp(App):
    """"""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.title = "Local Smart Video Summary"
        
        # 
        setup_logging('INFO')
        self.logger = logging.getLogger(__name__)
        
        # 
        self.screen_manager = None
        
        # 
        self.settings_data = self._load_default_settings()
        
        # 
        self._configure_fonts()
    
    def build(self):
        """"""
        self.logger.info("")
        
        # 
        self.screen_manager = ScreenManager()
        
        # 
        self.screen_manager.add_widget(MainWindow(name='main'))
        self.screen_manager.add_widget(UploadWindow(name='upload'))
        self.screen_manager.add_widget(ProcessingWindow(name='processing'))
        self.screen_manager.add_widget(ResultWindow(name='result'))
        self.screen_manager.add_widget(SettingsWindow(name='settings'))
        
        return self.screen_manager
    
    def navigate_to(self, screen_name: str):
        """"""
        if self.screen_manager:
            self.screen_manager.current = screen_name
    
    def _load_default_settings(self):
        """"""
        return {
            'whisper_model': 'base',
            'ollama_model': 'qwen2:7b',
            'ollama_host': 'localhost',
            'ollama_port': 11434,
            'language': 'auto',
            'summary_style': 'detailed',
            'output_formats': ['txt', 'srt', 'json'],
            'device': 'auto',
            'chunk_duration': 600,
            'auto_cleanup': True,
            'output_dir': './output',
            'temp_dir': './temp'
        }
    
    def get_settings(self):
        """"""
        return self.settings_data
    
    def update_settings(self, new_settings):
        """"""
        self.settings_data.update(new_settings)
    
    def _configure_fonts(self):
        """"""
        try:
            import platform
            from config import DESKTOP_CONFIG
            
            # 
            font_size_multiplier = DESKTOP_CONFIG.get('font_size_multiplier', 1.2)
            fonts_by_os = DESKTOP_CONFIG.get('fonts_by_os', {})
            
            # 
            current_os = platform.system().lower()
            if current_os == 'darwin':
                os_key = 'darwin'
            elif current_os == 'windows':
                os_key = 'win32'
            else:
                os_key = 'linux'
            
            # 
            os_font_config = fonts_by_os.get(os_key, {})
            primary_font = os_font_config.get('primary', 'Roboto')
            fallbacks = os_font_config.get('fallbacks', [])
            font_paths = os_font_config.get('font_paths', [])
            
            self.logger.info(f": {current_os} ({os_key})")
            self.logger.info(f": {primary_font}")
            
            # 
            available_font_path = None
            for font_path in font_paths:
                if os.path.exists(font_path):
                    available_font_path = font_path
                    self.logger.info(f": {font_path}")
                    break
            
            if available_font_path:
                # Kivy
                try:
                    LabelBase.register(name='CustomChineseFont', fn_regular=available_font_path)
                    # Kivy
                    font_list = ['CustomChineseFont'] + [primary_font] + fallbacks + ['Roboto']
                    Config.set('kivy', 'default_font', font_list)
                    self.logger.info(f": {available_font_path}")
                    self.logger.info(f"Kivy: {font_list}")
                except Exception as e:
                    self.logger.warning(f": {e}")
                    # 
                    font_list = [primary_font] + fallbacks + ['Roboto']
                    Config.set('kivy', 'default_font', font_list)
                    self.logger.info(f": {font_list}")
            else:
                # 
                font_list = [primary_font] + fallbacks + ['Roboto']
                Config.set('kivy', 'default_font', font_list)
                self.logger.info(f": {font_list}")
            
            # 
            Config.set('graphics', 'font_size_multiplier', str(font_size_multiplier))
            self.logger.info(f": {font_size_multiplier}")
                
        except Exception as e:
            self.logger.error(f": {e}")
            # 
            Config.set('graphics', 'font_size_multiplier', '1.0')

def main():
    """"""
    app = DesktopApp()
    app.run()

if __name__ == "__main__":
    main()